package org.example.what_mall.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.what_mall.util.UserHolder;
import org.example.what_mall.vo.UserVO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class OrdinaryInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("请求路径：{}:{}", request.getMethod(), request.getRequestURI());

        if(Objects.equals(request.getMethod(), "OPTIONS")){
            return true;
        }

        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)){
            return true;
        }

        String key = "what_mall:token:" + token;
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(key);
        if(map.isEmpty()){
            return true;
        }

        UserVO user = BeanUtil.fillBeanWithMap(map, new UserVO(), false);

        UserHolder.saveUser(user);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserHolder.removeUser();
    }
}
